package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import com.fsd.core.bean.Tree;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.fsd.core.service.impl.BaseServiceImpl;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.ParametersUtil;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.Z_base;
import com.fsd.admin.service.Z_baseService;
import com.fsd.admin.dao.Z_baseDao;

@Repository("z_baseServiceImpl")
public class Z_baseServiceImpl extends BaseServiceImpl<Z_base, String> implements Z_baseService{
    
    private static final Logger log = Logger.getLogger(Z_baseServiceImpl.class);
    private String depict = "";
    
    @Resource(name = "z_baseDaoImpl")
	public void setBaseDao(Z_baseDao Z_baseDao) {
		super.setBaseDao(Z_baseDao);
	}
	
	@Resource(name = "z_baseDaoImpl")
	private Z_baseDao objectDao;
    
    /**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
    @Override
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("f_deleted", "0"));
		c.addOrder(Order.asc("f_adddate"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("f_name", "%" + objectMap.get("name") + "%"));
			}
			if(objectMap.get("id") != null && !"".equals(objectMap.get("id"))){
				c.add(Restrictions.like("f_fid", "%" + objectMap.get("id") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
    
    /**
	 * 编辑对象
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
    @Override
	public Z_base save(Z_base obj, A_Employee employee) throws Exception{
        if(obj.getId() != null && !"".equals(obj.getId())){
            //修改
            Z_base old_obj = objectDao.get(obj.getId());
			old_obj.setF_name(obj.getF_name());
			old_obj.setF_contact(obj.getF_contact());
			old_obj.setF_phone(obj.getF_phone());
			old_obj.setF_floorspace(obj.getF_floorspace());
			old_obj.setF_address(obj.getF_address());
			old_obj.setF_website(obj.getF_website());
			old_obj.setF_bigimgurl(obj.getF_bigimgurl());
			old_obj.setF_imgurl(obj.getF_imgurl());
			old_obj.setF_abstract(obj.getF_abstract());
			old_obj.setF_collegeid(obj.getF_collegeid());
			old_obj.setF_collegename(obj.getF_collegename());
			old_obj.setF_projects(obj.getF_projects());
			old_obj.setF_achievement(obj.getF_achievement());

			//设置修改日期
            old_obj.setF_lastupdatedate(this.getData());
			//设置修改用户id
			old_obj.setF_updateemployeeid(employee.getId());
			//设置修改用户姓名
			old_obj.setF_updateemployeename(employee.getRealname());

			//如果所属基地发生变化，需要更新之前所属基地叶子节点信息和新所属基地叶子节点信息
			if(!obj.getF_fid().equals(old_obj.getF_fid())){
				String sql = "update z_base set f_isleaf = ? where id = ?";
				objectDao.executeSql(sql, "false", obj.getF_fid());

				sql = "select * from z_base where f_fid = ? and id <> ?";
				List<Z_base> list = objectDao.queryBySql1(sql, old_obj.getF_fid(), old_obj.getId());
				if(list == null || list.size() == 0){
					sql = "update z_base set f_isleaf = ? where id = ?";
					objectDao.executeSql(sql, "true", old_obj.getF_fid());
				}
			}
            old_obj.setF_fid(obj.getF_fid());
            old_obj.setF_fname(obj.getF_fname());
            objectDao.update(old_obj);
            return old_obj;
        }else{
            //添加
			//设置主键
            obj.setId(this.getUUID());
			//设置添加日期
			obj.setF_adddate(this.getData());
			//设置添加用户id
			obj.setF_addemployeeid(employee.getId());
			//设置添加用户姓名
			obj.setF_addemployeename(employee.getRealname());
			obj.setF_isleaf("true");
			//设置删除标志(0:正常 1：已删除)
			obj.setF_deleted("0");
			if(!obj.getF_fid().equals("FSDMAIN")){
				String sql = "update z_base set f_isleaf = ? where id = ?";
				objectDao.executeSql(sql, "false", obj.getF_fid());
			}
			objectDao.save(obj);
			return obj;
        }
    }
    
    /**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
    @Override
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		for (String id : dir) {
			//查询删除基地是否有子集
			String sql = "select * from z_base where f_fid = ?";
			List<Z_base> list = objectDao.queryBySql1(sql, id);
			if(list != null && list.size() > 0 ){
				throw new BusinessException("该基地有二级基地，请先删除该基地的二级基地信息");
			}
			Z_base base = objectDao.get(id);
			objectDao.delete(id);
			sql = "select * from z_base where f_fid = ?";
			list = objectDao.queryBySql1(sql, base.getF_fid());
			if(list == null || list.size() == 0){
				sql = "update z_base set f_isleaf = ? where id = ?";
				objectDao.executeSql(sql, "true", base.getF_fid());
			}
		}
	}
    
    /**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
    @Override
	public Z_base getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		Z_base obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		
		return obj;
	}

	/**
	 * 异步加载基地树结构
	 * @param fid
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getAsyncObjectTree(String fid, A_Employee employee) throws Exception{
    	List<Z_base>  list = getListByFid(fid);
		List<Tree> treelist = new ArrayList<>();
		Tree tree = null;
    	if(list != null && list.size() > 0){
			for (Z_base z_base : list) {
				tree = new Tree();
				tree.setId(z_base.getId());
				tree.setText(z_base.getF_name());
				tree.setLeaf(Boolean.valueOf(z_base.getF_isleaf()));
				treelist.add(tree);
			}
		}
    	return treelist;
	}

	/**
	 * 根据FID加载列表
	 * @param fid
	 * @return
	 * @throws Exception
	 */
	public List<Z_base> getListByFid(String fid) throws Exception{
    	String sql = "select * from z_base where f_fid = ? and f_deleted = 0";
    	return objectDao.queryBySql1(sql, fid);
	}
}
